package com.example.myapplication2;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class SharedPrefencesActivity extends AppCompatActivity implements View.OnClickListener {

    EditText nameEdit2;
    EditText ageEdit2;
    CheckBox passwordCheckBox;
    SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_prefences);
        nameEdit2 = findViewById(R.id.nameEdit2);
        ageEdit2 = findViewById(R.id.ageEdit2);
        passwordCheckBox = findViewById(R.id.passwordCheckBox);
        //设置监听
        findViewById(R.id.save).setOnClickListener(this);
        //获取SharedPrefences对象
        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        reload();
    }

    private void reload() {
        //在启动这个舞台的时候,加载配置
        String name = sharedPreferences.getString("name", "无....");
        nameEdit2.setText(name);
        int age = sharedPreferences.getInt("age", 0);
        if (age!=0){
            //避免Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x27a29 错误,使用字符串
            ageEdit2.setText(age+"");
        }
        passwordCheckBox.setChecked(sharedPreferences.getBoolean("checkBox", false));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.save:
                save();
                break;
        }
    }

    private void save() {
        //进入编辑模式
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString("name",nameEdit2.getText().toString());
        edit.putInt("age", Integer.parseInt(ageEdit2.getText().toString()));
        edit.putBoolean("checkBox",passwordCheckBox.isChecked());
        //提交
        edit.commit();
    }
}